<!-- 企业微信预约会议 -->
<template>
  <div style="padding: 40px; overflow-y: auto">
    <a-form layout="vertical">
      <!-- 会议类型 -->
      <a-form-item label="会议类型">
        <a-button
          style="background-color: rgb(179, 179, 179)"
          @click="meetingTypeFc(1)"
        >
          <template #icon>
            <icon-desktop />
          </template>
          云会议
        </a-button>
        <a-button
          style="background-color: rgb(179, 179, 179); margin-left: 10px"
          @click="meetingTypeFc(0)"
          >
<template #icon>
            <icon-relation />
          </template>
          现场会议
</a-button
        >
      </a-form-item>
      <div v-if="formData.meetType === 0">
        <div style="gap: 10px; display: flex">
          <a-select
            v-model="selectedFactoryId"
            :style="{ width: '10vw' }"
            placeholder="请选择厂区"
            @change="onFactoryChange"
          >
            <a-option
              v-for="factory in factoryList"
              :key="factory.id"
              :value="factory.id"
              :label="factory.name"
            />
          </a-select>
          <a-select
            v-model="selectedBuildingId"
            :style="{ width: '10vw' }"
            placeholder="请选择办公楼"
            @change="onBuildingChange"
          >
            <a-option
              v-for="building in buildingList"
              :key="building.id"
              :value="building.id"
              :label="building.name"
            >
            </a-option>
          </a-select>
          <a-select
            :style="{ width: '10vw' }"
            placeholder="请选择楼层"
            @change="availableFloorSelectChange"
          >
            <a-option
              v-for="item of availableFloorList"
              :key="item.floor"
              :value="item.floor"
              :label="item.floor"
            />
          </a-select>
        </div>
        <div v-if="meetingRoomList.length > 0" style="margin-top: 20px;">
          <a-radio-group
            direction="vertical"
            style="height: 30vh; overflow: auto"
           @change="meetingRoomrediogroup"
          >
            <template v-for="item in meetingRoomList" :key="item">
              <a-radio :value="item.id" style="padding: 5px 5px">
                <template #radio="{ checked }">
                  <a-space
                    align="start"
                    class="custom-radio-card"
                    :class="{ 'custom-radio-card-checked': checked }"
                  >
                    <div className="custom-radio-card-mask">
                      <div className="custom-radio-card-mask-dot" />
                    </div>
                    <div>
                      <div className="custom-radio-card-title"></div>
                      <a-typography-text
                        type="secondary"
                        style="display: flex; align-items: center"
                      >
                        <div style="">
                          <a-image
                            width="150"
                            :src="item.imageUrl"
                          />
                        </div>
                        <div style="margin-left: 5vw;">
                          <div>{{ item.name }}</div>
                          <div>编号: {{ item.capacity }}</div>
                          <div>可容纳{{ item.capacity }}人</div>
                        </div>
                      </a-typography-text>
                    </div>
                  </a-space>
                </template>
              </a-radio>
            </template>
          </a-radio-group>
        </div>
      </div>
      <!-- 会议主题 -->
      <a-form-item label="会议主题">
        <a-input v-model="formData.subject" placeholder="请输入会议主题" />
      </a-form-item>

      <!-- 会议开始时间 -->
      <a-form-item label="开始时间">
        <a-date-picker
          v-model="formData.startTime"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          :time-picker-props="{
            format: 'HH:mm',
            hideDisabledOptions: true,
            disabledHours: [],
          }"
          :disabled-time="disabledTime"
          @change="onStartTimeChange"
        />
      </a-form-item>

      <!-- 持续时间 -->
      <a-form-item label="持续时间（分钟）">
        <a-input-number v-model="formData.length" :min="1" />
      </a-form-item>
      <!-- 是否开启周期会议 -->
      <a-form-item label="重复">
        <a-select
          v-model="recurrenceType"
          placeholder="请选择重复类型"
          @change="handleRecurrenceTypeChange"
        >
          <a-option value="none">不重复</a-option>
          <a-option value="daily">每天重复</a-option>
          <a-option value="workdays">每个工作日重复</a-option>
          <a-option value="weekly">每周重复</a-option>
          <a-option value="biweekly">每两周重复</a-option>
          <a-option value="monthly">每月重复</a-option>
          <a-option value="custom">自定义...</a-option>
        </a-select>
      </a-form-item>

      <div v-if="recurrenceType !== 'none' && recurrenceType !== null">
        <a-form-item label="循环开始日期">
          <a-date-picker v-model="cycleParams.startDate" format="YYYY-MM-DD" />
        </a-form-item>

        <a-form-item label="循环结束日期">
          <a-date-picker v-model="cycleParams.endDate" format="YYYY-MM-DD" />
        </a-form-item>

        <template v-if="recurrenceType === 'custom'">
          <a-form-item label="循环类型">
            <a-select
              v-model="cycleParams.cycle"
              placeholder="请选择循环类型"
              @change="onCycleChange"
            >
              <a-option value="Day">日</a-option>
              <a-option value="Week">周</a-option>
              <a-option value="Month">月</a-option>
            </a-select>
          </a-form-item>

          <a-form-item label="间隔周期(日：每隔几日  周：每隔几周  月：每隔几月)">
            <a-input-number v-model="cycleParams.interval" :min="1" />
          </a-form-item>

          <template v-if="cycleParams.cycle === 'Week'">
            <a-form-item label="每周选择">
              <a-checkbox-group v-model="cycleParams.point">
                <a-checkbox value="1">星期一</a-checkbox>
                <a-checkbox value="2">星期二</a-checkbox>
                <a-checkbox value="3">星期三</a-checkbox>
                <a-checkbox value="4">星期四</a-checkbox>
                <a-checkbox value="5">星期五</a-checkbox>
                <a-checkbox value="6">星期六</a-checkbox>
                <a-checkbox value="7">星期天</a-checkbox>
              </a-checkbox-group>
            </a-form-item>
          </template>

          <template v-if="cycleParams.cycle === 'Month'">
            <a-form-item label="每月选择">
              <a-checkbox-group v-model="cycleParams.point">
                <a-checkbox value="1">1号</a-checkbox>
                <a-checkbox value="2">2号</a-checkbox>
                <a-checkbox value="3">3号</a-checkbox>
                <a-checkbox value="4">4号</a-checkbox>
                <a-checkbox value="5">5号</a-checkbox>
                <a-checkbox value="6">6号</a-checkbox>
                <a-checkbox value="7">7号</a-checkbox>
                <a-checkbox value="8">8号</a-checkbox>
                <a-checkbox value="9">9号</a-checkbox>
                <a-checkbox value="10">10号</a-checkbox>
                <a-checkbox value="11">11号</a-checkbox>
                <a-checkbox value="12">12号</a-checkbox>
                <a-checkbox value="13">13号</a-checkbox>
                <a-checkbox value="14">14号</a-checkbox>
                <a-checkbox value="15">15号</a-checkbox>
                <a-checkbox value="16">16号</a-checkbox>
                <a-checkbox value="17">17号</a-checkbox>
                <a-checkbox value="18">18号</a-checkbox>
                <a-checkbox value="19">19号</a-checkbox>
                <a-checkbox value="20">20号</a-checkbox>
                <a-checkbox value="21">21号</a-checkbox>
                <a-checkbox value="22">22号</a-checkbox>
                <a-checkbox value="23">23号</a-checkbox>
                <a-checkbox value="24">24号</a-checkbox>
                <a-checkbox value="25">25号</a-checkbox>
                <a-checkbox value="26">26号</a-checkbox>
                <a-checkbox value="27">27号</a-checkbox>
                <a-checkbox value="28">28号</a-checkbox>
                <a-checkbox value="29">29号</a-checkbox>
                <a-checkbox value="30">30号</a-checkbox>
                <a-checkbox value="31">31号</a-checkbox>
              </a-checkbox-group>
              <span v-if="invalidDateWarning" style="color: red"
                >请注意，某些日期在二月份可能不存在。</span
              >
            </a-form-item>
          </template>
        </template>
      </div>
      <!-- 媒体类型选择器 -->
      <a-form-item label="媒体类型">
        <a-select
          v-model="formData.mediaTypes"
          placeholder="请选择媒体类型"
          allow-clear
        >
          <a-option value="Voice">音频</a-option>
          <a-option value="Video">视频</a-option>
        </a-select>
      </a-form-item>
      <!-- 来宾设置 -->
      <!-- 来宾设置 -->
      <a-form-item label="来宾设置" class="form-item">
        <div class="guest-settings">
          <!-- 是否免密的复选框 -->
          <a-checkbox
            v-model="formData.confConfigInfo.isGuestFreePwd"
            class="form-checkbox"
          >
            关闭来宾密码
          </a-checkbox>

          <!-- 如果免密，显示来宾密码输入框 -->
          <a-input
            v-if="!formData.confConfigInfo.isGuestFreePwd"
            v-model="formData.confConfigInfo.guestPwd"
            placeholder="请输入来宾密码"
            class="form-input"
          />

          <!-- 限制范围文字 -->
          <div class="restriction-label">限制范围</div>

          <!-- 呼入限制选择 -->
          <a-select
            v-model="formData.confConfigInfo.callInRestriction"
            placeholder="请选择加入限制"
            class="full-width"
          >
            <a-option :value="0">无限制</a-option>
            <a-option :value="1">仅限内部用户</a-option>
          </a-select>

          <!-- 是否开启等候室 -->
          <a-checkbox
            v-model="formData.confConfigInfo.enableWaitingRoom"
            class="form-checkbox"
          >
            开启等候室
          </a-checkbox>
        </div>
      </a-form-item>
      <a-form-item label="与会人" class="invite-container">
        <div>
          <div class="invite-header">
            <a-button type="outline" class="white-btn" @click="showInviteModal = true"
              >
邀请与会人
</a-button
            >
          </div>

          <div v-if="selectedUsers.length > 0" class="selected-users">
            <div
              v-for="(user, index) in selectedUsers"
              :key="user.userid"
              class="user-card"
              @mouseover="hoverIndex = index"
              @mouseleave="hoverIndex = -1"
            >
              <img
                :src="user.avatar || 'https://via.placeholder.com/30'"
                class="user-avatar"
              />
              <span class="user-name">{{ user.name }}</span>

              <!-- X 按钮 -->
              <span
                v-if="hoverIndex === index"
                class="delete-btn"
                @click="removeUser(index)"
                >✖</span
              >
            </div>
          </div>
          <div style="padding: 20px 0px">
            <a-form-item label="预约人" class="invite-container">
              <a-tree-select
                v-model="treeUser"
                :data="userTreeDataReservation"
                placeholder="请选择预约人"
                style="width: 300px"
                @change="treeUserChange()"
              ></a-tree-select>
            </a-form-item>
          </div>
        </div>
      </a-form-item>
      <div
        class="invite-header"
        style="margin-left: auto; padding: 0px 100px 0px 0px"
      >
        <a-popconfirm content="确认提交吗?" @ok="onScheduleMeetingSubmit">
          <a-button type="primary">提交</a-button>
        </a-popconfirm>
      </div>
    </a-form>

    <a-modal
      v-model:visible="showInviteModal"
      title="邀请与会人"
      @ok="handleInviteConfirm"
    >
      <a-tree
        v-model:checked-keys="checkedUserIds"
        checkable
        :data="userTreeData"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { ref, watch } from 'vue'
import { debounce } from 'lodash-es'
import { Message } from '@arco-design/web-vue'
import { useRoute } from 'vue-router'
import type { IMeeting } from './type'
import {
  getAvailableFloor,
  getAvailablerooms,
  getBuildingList,
  getFactoryList,
  getMeetingList,
  getUserTree,
  scheduleMeeting
} from '@/apis/startApp/meeting'
import { useForm } from '@/hooks'
// 获取用户树

defineOptions({ name: 'StartApp' })
// 控制邀请弹窗
const showInviteModal = ref(false)
// 控制预约会议弹窗
const showScheduleMeetingModal = ref(false)
const hoverIndex = ref(-1) // 记录鼠标悬停的索引
const treeUser = ref() // 预约人的树选择值
// 选择的厂区和办公楼
const selectedFactoryId = ref<number | null>(null)

const availableFloorList = ref([]) // 楼层列表
const selectedBuildingId = ref<number | null>(null)
// 存储树形结构数据
const userTreeData = ref([])
const userTreeDataReservation = ref([])
// 已选中的 `userid`（最终返回）
const selectedUsers = ref<{ userid: string, name: string, avatar: string }[]>(
  []
)

// 绑定到 `a-tree` 组件的 `checkedUserIds`
const checkedUserIds = ref<string[]>([])
const selectUserIds = ref<string[]>([])
const meetingRoomList = ref<
  {
    id: number
    name: string
    floor: string
    capacity: number
    imageUrl: string
  }[]
>([])

const route = useRoute()
let userId
  = route.params.userId?.toString() || route.query.userId?.toString() || null
const meetingLoading = ref(false)
const meetingList = ref<IMeeting[]>([])
const noDataState = ref(false)
// 厂区数据
const factoryList = ref<{ id: number, name: string }[]>([])
const buildingList = ref<{ id: number, name: string }[]>([])
// 是否启用周期会议
const isRecurringMeeting = ref(false)
// 重复类型
const recurrenceType = ref('none')
// 周期会议参数状态
const cycleParams = ref({
  startDate: null as string | null,
  endDate: null as string | null,
  cycle: '',
  interval: 1,
  point: [] as (string | number)[] // 周期点
})

// 用于标识是否存在无效日期的警告
const invalidDateWarning = ref(false)
// 选中的日期状态
const selectedDate = ref(dayjs().format('YYYY-MM-DD'))
/**
 * 会议类型切换的值
 */
const meetingTypeFc = (type: number) => {
  formData.value.meetType = type
}
/**
 * 选择预约人
 */
const treeUserChange = () => {
  userId = treeUser.value
  console.log(userId)
}
watch(selectedDate, (newDate) => {
  // fetchRoomStatus(newDate);
})
// 在办公楼变化时调用此方法
watch(selectedBuildingId, (newBuildingId) => {
  if (newBuildingId) {
    // fetchRoomStatus(newBuildingId);
  }
})
/**
 * 删除与会人事件
 */
const removeUser = (index: number) => {
  const removedUserId = selectedUsers.value[index].userid

  // 1️⃣ 从 `selectedUsers` 里删除该用户
  selectedUsers.value.splice(index, 1)

  // 2️⃣ 同步更新 `a-tree` 组件的 `checkedUserIds`
  checkedUserIds.value = checkedUserIds.value.filter(
    (id) => id !== removedUserId
  )

  selectUserIds.value = selectUserIds.value.filter(
    (id) => id !== removedUserId
  )
}
// 处理周期类型的变化
const onCycleChange = (value) => {
  cycleParams.value.cycle = value

  if (value === 'Day') {
    cycleParams.value.point = [] // 清空周期点
  } else if (value === 'Week') {
    cycleParams.value.point = [] // 重新设置为数组，以便用户选择周几
  } else if (value === 'Month') {
    cycleParams.value.point = null // 清掉 `point`
  }
}
// 会议表单数据
const formData = ref({
  subject: '',
  startTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  length: 45,
  mediaTypes: '', // ✅ 默认 `HDVideo`
  meetRoomId: undefined, // ✅ 线下会议时必填
  meetType: 1, // 1=线上会议, 0=线下会议

  // ✅ 会议配置信息
  confConfigInfo: {
    isGuestFreePwd: false,
    callInRestriction: 0,
    guestPwd: '',
    enableWaitingRoom: false
  },

  // 可选的循环会议参数
  cycleParams: {
    startDate: null,
    endDate: null,
    cycle: '',
    interval: 1, // 默认间隔为1
    point: [] // 选择的周期点
  }
})

// 切换周期会议状态
const toggleRecurringMeeting = () => {
  if (!isRecurringMeeting.value) {
    // 如果取消勾选，重置周期参数
    cycleParams.value = {
      startDate: null,
      endDate: null,
      cycle: '',
      interval: 1,
      point: [] as (string | number)[]
    }
    // 同时重置下拉框选择
    recurrenceType.value = 'none'
  } else {
    // 如果勾选，默认设置为自定义
    recurrenceType.value = 'custom'
  }
}
watch(
  selectedUsers,
  (newUsers) => {
    checkedUserIds.value = newUsers.map((user) => user.userid)
  },
  { deep: true }
)
// 自定义时间禁用设置，使分钟只能选择每15分钟的时间
const disabledTime = () => {
  return {
    disabledHours: () => [],
    disabledMinutes: (hour) => {
      // 禁用非15的倍数的分钟
      return Array.from({ length: 60 }, (_, i) =>
        i % 15 !== 0 ? i : null).filter((i) => i !== null)
    }
  }
}
// 获取厂区数据
const fetchFactories = async () => {
  try {
    factoryList.value = await getFactoryList()
  } catch (error) {
    console.error('获取厂区失败:', error)
  }
}

// 当厂区变化时，获取办公楼数据
const onFactoryChange = async (value) => {
  buildingList.value = await getBuildingList(value)
}
/**
 * 会议室选择事件
 * @param value 楼层id值
 */
const meetingRoomrediogroup = (value) => {
  formData.value.meetRoomId = value
}
/**
 * 根据办公楼id获取楼层列表
 * @param value 办公楼id
 */
const availableFloorChange = async (value) => {
  const res = await getAvailableFloor(value)
  availableFloorList.value = res.data
}
/**
 * 选择办公楼事件
 */
const onBuildingChange = async (value?) => {
  availableFloorChange(value)
}
/**
 * 楼层选择事件
 */
const availableFloorSelectChange = async (value) => {
  const res = await getAvailablerooms({
    floor: value,
    startTime: formData.value.startTime,
    continuedTime: formData.value.length,
    buildingId: selectedBuildingId.value
  })
  console.log(res)
  meetingRoomList.value = res.data
}

// 在表单中的开始时间和持续时间变化时，执行相关逻辑
watch(
  () => [formData.value.startTime, formData.value.length],
  ([newStartTime, newLength], [oldStartTime, oldLength]) => {
    if (
      formData.value.meetType === 0
      && (newStartTime !== oldStartTime || newLength !== oldLength)
    ) {
      onBuildingChange()
    }
  }
)

watch(
  () => formData.value.meetType,
  (newValue) => {
    console.log('会议类型变更:', newValue)
    console.log('会议类型变更:', formData.value.meetType)
  }
)
// 关闭预约会议弹窗
// 转换数据格式（确保 `userid` 绑定正确）
const transformTreeData = (data: any[]) => {
  return data.map((node) => ({
    title: node.name,
    key: node.type === 'user' ? node.userid : node.id?.toString(), // ✅ 用户用 userid，部门用 id
    value: node.type === 'user' ? node.userid : node.id?.toString(), // ✅ 用户用 userid，部门用 id
    selectable: node.type === 'user', // ✅ 只能选用户
    children:
      node.children && node.children.length > 0
        ? transformTreeData(node.children)
        : [],
    avatar: node.avatar || null // ✅ 头像
  }))
}
// 递归查找用户节点（根据 userid）
const findUserById = (tree, userid) => {
  for (const node of tree) {
    if (node.value === userid) return node
    if (node.children) {
      const found = findUserById(node.children, userid)
      if (found) return found
    }
  }
  return null
}

// 监听用户选择，点击 "确定" 时存入 `selectedUsers`
const handleInviteConfirm = () => {
  selectedUsers.value = checkedUserIds.value
    .map((userid) => {
      const userNode = findUserById(userTreeData.value, userid)
      return userNode
        ? { userid, name: userNode.title, avatar: userNode.avatar || '' }
        : null
    })
    .filter(Boolean)

  showInviteModal.value = false // ✅ 关闭弹窗
}

// 获取用户树数据
// 获取用户树数据
const fetchUserTree = async () => {
  try {
    const rawData = await getUserTree()
    userTreeData.value = transformTreeData(rawData)
    userTreeDataReservation.value = transformTreeData(rawData)
  } catch (error) {
    console.error('获取用户树失败:', error)
  }
}
const { form } = useForm({
  keyword: ''
})
/**
 * 获取会议列表
 */
const fatchMeetingList = debounce(() => {
  const params = { userId, ...form }
  meetingLoading.value = true
  getMeetingList(params)
    .then((res) => {
      meetingList.value = res.data
      noDataState.value = res.data.length == 0
      meetingLoading.value = false
    })
    .catch((_err) => {
      noDataState.value = true
      meetingLoading.value = false
    })
}, 500)

watch(form, (_newValue, _oldValue) => {
  fatchMeetingList()
})
document.addEventListener(
  'touchmove',
  (e) => {
    e.passive = true
  },
  { capture: false, passive: true }
)
watch(selectedDate, (newDate) => {
  // fetchRoomStatus(newDate);
})
const onStartTimeChange = (timeString) => {
  // 将时间字符串转换为dayjs对象
  const dateTime = dayjs(formData.value.startTime)
  // 更新开始时间，将秒数设置为00
  formData.value.startTime = dateTime
    .set('hour', dayjs(timeString).hour())
    .set('minute', dayjs(timeString).minute())
    .set('second', 0)
    .format('YYYY-MM-DD HH:mm:ss')
}
// 重置表单函数
const resetForm = () => {
  formData.value = {
    subject: '',
    startTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    length: 45,
    mediaTypes: '',
    meetRoomId: undefined,
    meetType: 1,
    confConfigInfo: {
      isGuestFreePwd: false,
      callInRestriction: 0,
      guestPwd: '',
      enableWaitingRoom: false
    },
    cycleParams: {
      startDate: null,
      endDate: null,
      cycle: '',
      interval: 1,
      point: [] as (string | number)[]
    } // 重置循环会议参数
  }
  selectedFactoryId.value = null
  selectedBuildingId.value = null
  selectedUsers.value = []
  checkedUserIds.value = []
  isRecurringMeeting.value = false // 重置周期会议状态
  recurrenceType.value = 'none' // 重置重复类型
  treeUser.value = null
}
// 提交预约会议
const onScheduleMeetingSubmit = async () => {
  if (!selectedUsers.value.length) {
    return Message.error('请选择与会者！')
  }

  if (!formData.value.subject) {
    return Message.error('请输入会议主题！')
  }

  if (!formData.value.startTime) {
    return Message.error('请选择会议开始时间！')
  }
  if (formData.value.meetType === 0 && !formData.value.meetRoomId) {
    return Message.error('请选择会议室！')
  }
  if (!formData.value.length) {
    return Message.error('请输入会议持续时间！')
  }

  if (!userId) {
    return Message.error('用户 ID 不能为空！')
  }

  // 对循环会议参数进行验证
  if (recurrenceType.value !== 'none') {
    if (!cycleParams.value.endDate) {
      return Message.error('请选择循环结束日期！')
    }

    if (cycleParams.value.cycle === 'Week' && (!cycleParams.value.point || cycleParams.value.point.length === 0)) {
      return Message.error('请选择循环的周几！')
    }

    if (cycleParams.value.cycle === 'Month' && (!cycleParams.value.point || cycleParams.value.point.length === 0)) {
      return Message.error('请选择循环的日期！')
    }
  }

  const requestData = {
    userId, // ✅ 取自 URL
    subject: formData.value.subject,
    startTime: formData.value.startTime,
    length: formData.value.length,
    mediaTypes: formData.value.mediaTypes || 'HDVideo', // ✅ 默认 `HDVideo`
    meetRoomId: formData.value.meetRoomId,
    meetType: formData.value.meetType,

    // ✅ 会议配置信息
    confConfigInfo: {
      isGuestFreePwd: formData.value.confConfigInfo?.isGuestFreePwd || false,
      callInRestriction: formData.value.confConfigInfo?.callInRestriction || 0,
      guestPwd: formData.value.confConfigInfo?.guestPwd || '',
      enableWaitingRoom:
        formData.value.confConfigInfo?.enableWaitingRoom || false
    },

    // ✅ 如果是循环会议才提交 `cycleParams`
    cycleParams: recurrenceType.value !== 'none'
      ? {
          startDate: cycleParams.value.startDate,
          endDate: cycleParams.value.endDate,
          cycle: cycleParams.value.cycle,
          interval: cycleParams.value.interval,
          point: cycleParams.value.point
        }
      : undefined,

    // ✅ 与会者列表
    attendees: selectedUsers.value.map((user) => ({
      accountId: user.userid,
      appId: '9dbd6b334e744eada42b45b3bf6b8402'
    }))
  }

  console.log('提交预约会议请求:', requestData)
  try {
    await scheduleMeeting(requestData)
    Message.success('会议预约成功！')
    // 成功后调用重置函数
    resetForm()
    fetchUserTree()
    showScheduleMeetingModal.value = false
    // 调用 fetchMeetingList 重新获取会议列表
    await fatchMeetingList()
  } catch (error) {
    Message.error('预约会议失败，请重试！')
    console.error('预约会议失败:', error)
  }
  meetingRoomList.value = []
}

// 处理重复类型变化
const handleRecurrenceTypeChange = (value) => {
  // 如果选择了不重复，则相当于关闭周期会议
  isRecurringMeeting.value = value !== 'none'

  // 根据选择的重复类型设置循环参数
  if (value === 'none') {
    // 重置周期参数
    cycleParams.value = {
      startDate: null,
      endDate: null,
      cycle: '',
      interval: 1,
      point: [] as (string | number)[]
    }
  } else {
    // 设置开始日期为当前会议的开始日期
    if (!cycleParams.value.startDate) {
      cycleParams.value.startDate = dayjs(formData.value.startTime).format('YYYY-MM-DD')
    }

    // 根据不同的重复类型设置对应的参数
    switch (value) {
      case 'daily':
        cycleParams.value.cycle = 'Day'
        cycleParams.value.interval = 1
        cycleParams.value.point = []
        break
      case 'workdays':
        cycleParams.value.cycle = 'Week'
        cycleParams.value.interval = 1
        cycleParams.value.point = ['1', '2', '3', '4', '5'] // 周一到周五
        break
      case 'weekly':
        cycleParams.value.cycle = 'Week'
        cycleParams.value.interval = 1
        // 设置为会议开始日期的星期几
        const dayOfWeek = dayjs(formData.value.startTime).day()
        cycleParams.value.point = [dayOfWeek === 0 ? '7' : dayOfWeek.toString()]
        break
      case 'biweekly':
        cycleParams.value.cycle = 'Week'
        cycleParams.value.interval = 2
        // 设置为会议开始日期的星期几
        const dayOfWeek2 = dayjs(formData.value.startTime).day()
        cycleParams.value.point = [dayOfWeek2 === 0 ? '7' : dayOfWeek2.toString()]
        break
      case 'monthly':
        cycleParams.value.cycle = 'Month'
        cycleParams.value.interval = 1
        // 设置为会议开始日期的日期
        const dayOfMonth = dayjs(formData.value.startTime).date().toString()
        cycleParams.value.point = [dayOfMonth]
        break
      case 'custom':
        // 自定义模式，不自动设置参数，让用户自行选择
        if (!cycleParams.value.cycle) {
          cycleParams.value.cycle = 'Day'
        }
        break
    }
  }
}

onMounted(() => {
  fetchUserTree()
  // 组件初始化时获取厂区数据
  fetchFactories()
  selectedDate.value = dayjs().format('YYYY-MM-DD') // 初始化当天的日期
  if (selectedBuildingId.value) {
    // fetchRoomStatus(selectedDate.value);
  }
})
</script>

  <style lang="scss" scoped>
.name-box,
.date,
.promoter,
.participant {
  padding-bottom: 10px;
}

.form-checkbox {
  margin-top: 20px;
  /* 调整上方间距 */
  margin-bottom: 20px;
  /* 调整下方间距 */
}

/* 为会议室图片和选项调整样式 */
.meeting-room-option {
  display: flex;
  align-items: center;

  .room-image {
    width: 40px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
    margin-right: 10px;
  }

  span {
    font-size: 14px;
    line-height: 1.2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.large-image {
  width: 100%;
  /* 设置大图宽度适应模态框 */
  height: auto;
  /* 自动调整高度以保持比例 */
}

.room-image {
  width: 50px;
  /* 设置图片宽度，可以根据需要调整 */
  height: 50px;
  /* 设置图片高度，可以根据需要调整 */
  object-fit: cover;
  /* 保持图片比例并裁剪 */
  border-radius: 4px;
  /* 设置圆角 */
  flex-shrink: 0;
  /* 防止图片被压缩 */
}

.name-box {
  display: flex;
  justify-content: space-between;

  .name {
    font-weight: bold;
    flex: 1;
  }

  .status {
    font-weight: bold;
  }

  .status-0 {
    color: #ec7f39;
  }

  .status-1 {
    color: #008000;
  }

  .status-3 {
    color: #ff0000;
  }
}

.promoter,
.participant {
  color: #6c676b;
  font-size: 13px;
}

.occupancy-slot.occupied {
  background-color: #90caf9;
}

.noData {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arco-spin {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.pc {
  display: flex;
  height: 100vh;

  .container-l {
    background-color: #f7f7f7;
    width: 200px;
    height: 100%;
    box-sizing: border-box;
    padding: 20px;

    .btn {
      width: 100%;
    }
  }

  .container-r {
    background-color: #ffffff;
    flex: 1;
    height: 100%;
    box-sizing: border-box;
    padding: 0 20px;
    display: flex;
    flex-direction: column;

    .search-query {
      margin-top: 20px;
    }

    .meeting-list {
      flex: 1;
      overflow-y: scroll;

      .title {
        color: #878986;
        padding: 15px 0;
        border-bottom: 2px solid #f6f6f6;
        font-weight: bold;
      }

      .meeting-item {
        padding: 15px 0;
        border-bottom: 2px solid #f9f9f9;

        .status {
          margin-right: 15px;
        }
      }
    }
  }
}

/* 预约会议按钮 */
.btn {
  width: 100%;
  margin-top: 35px;
}

.h5 {
  font-size: 17px;
  background-color: #ffffff;
  height: 100vh;
  padding: 10px;
  box-sizing: border-box;

  .container {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    /* 确保里面的滚动有效 */
  }

  .meeting-list {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 90px;
  }

  .meeting-info {
    display: flex;

    .title {
      width: 60px;
      text-align: center;
      margin-right: 10px;
      margin-top: 20px;
      box-sizing: border-box;
    }

    .meeting {
      flex: 1;

      .meeting-item {
        background-color: #f8f8f8;
        border-radius: 10px;
        padding: 15px;
        margin-bottom: 15px;

        .participant {
          padding: 0;
        }
      }
    }
  }
}

.date-selector {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  a-button {
    margin-right: 10px;
  }

  span {
    margin: 0 10px;
    font-size: 16px;
    font-weight: bold;
  }

  a-icon {
    cursor: pointer;
  }
}

.invite-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
  width: 100%;
  /* 确保整个组件不会超出 */
}

.selected-users {
  display: flex;
  flex-wrap: wrap;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  /* ✅ 每行最多 4 个 */
  gap: 10px;
  width: 100%;
  max-width: 100%;
  /* ✅ 限制最大宽度，避免超出 */
  overflow-x: hidden;
  /* ✅ 禁止横向滚动 */
  margin-top: 1rem;
}

.user-card {
  display: flex;
  align-items: center;
  background: #f8f8f8;
  padding: 8px;
  border-radius: 4px;
  position: relative;
  width: calc(50% - 10px);
  margin-left: 20px;
  width: 90px;
  /* 确保两列显示 */
}

.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 8px;
}

.user-name {
  font-size: 14px;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* X 按钮 */
.delete-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  background: red;
  color: white;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
}

/* 鼠标悬停时显示 X */
.user-card:hover .delete-btn {
  opacity: 1;
}

.room-status {
  max-height: 400px;
  overflow-y: auto;
}

.room-status table {
  width: 100%;
  border-collapse: collapse;
}

.room-status th,
.room-status td {
  border: 1px solid #ddd;
  padding: 8px;
}

.timeline {
  height: 500px;
  width: 100%;
  overflow-y: auto;
}

.timeline-header {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  /* 增加与下方内容的间距 */
}

.hour-label {
  flex: 1 0 calc(100% / 24);
  /* 调整为24份以确保宽度固定 */
  text-align: center;
  font-weight: bold;
  padding: 10px 0;
  border-right: 1px solid #ddd;
  box-sizing: border-box;
  font-size: 14px;
}

.timeline-container {
  margin-bottom: 40px;
}

.room-info {
  font-weight: bold;
  margin-bottom: 10px;
}

.timeline-bar {
  display: flex;
  height: 80px;
  border: 1px solid #ddd;
}

.occupancy-slot {
  flex: 1 0 calc(100% / 96);
  /* 确保每小时有4个格子 */
  height: 80px;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

a-form {
  max-width: 100%;
  padding: 10px;
  box-sizing: border-box;

  .ant-form-item {
    margin-bottom: 20px;
  }
}

/* 针对移动端输入框和选择器的调整 */
a-input,
a-select,
a-date-picker,
a-input-number {
  width: 100%;
  /* 让所有输入相关元素宽度自适应 */
  font-size: 16px;
  /* 增大字体以提高可读性 */
}

a-checkbox,
a-button {
  margin-top: 10px;
}
.custom-radio-card {
  padding: 10px 16px;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  width: 40vw;
  box-sizing: border-box;
}

.custom-radio-card-mask {
  height: 14px;
  width: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 100%;
  border: 1px solid var(--color-border-2);
  box-sizing: border-box;
}

.custom-radio-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 100%;
}

.custom-radio-card-title {
  color: var(--color-text-1);
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
}

.custom-radio-card:hover,
.custom-radio-card-checked,
.custom-radio-card:hover .custom-radio-card-mask,
.custom-radio-card-checked .custom-radio-card-mask {
  border-color: rgb(var(--primary-6));
}

.custom-radio-card-checked {
  background-color: var(--color-primary-light-1);
}

.custom-radio-card:hover .custom-radio-card-title,
.custom-radio-card-checked .custom-radio-card-title {
  color: rgb(var(--primary-6));
}

.custom-radio-card-checked .custom-radio-card-mask-dot {
  background-color: rgb(var(--primary-6));
}
</style>
